Xml is as follows.
<System>
<ID></ID>
<Name></Name>
<Monitor>
<ID></ID>
<Type></Type>
<Alert>
<ID></ID>
<Status></Status>
</Alert>
<Alert>
<ID></ID>
<Status></Status>
</Alert>
</Monitor>
</System>
<System>
<ID></ID>
<Name></Name>
<Monitor>
<ID></ID>
<Type></Type>
<Alert>
<ID></ID>
<Status></Status>
</Alert>
</Monitor>
</System>
I want to traverse it like this
XElement xmlDoc = XElement.Load(@"xml");
var q = from el in xmlDoc.Elements("System") select el;
foreach(el in q) {
Console.WriteLine(el.ID);
Console.WriteLine(el.Name);
if (el.Monitor) {
foreach (mon in el.Monitor) {
Console.WriteLine(el.ID);
Console.WriteLine(el.Type);
if (mon.Alert) {
foreach (alert in mon.Alert) {
Console.WriteLine(alert.ID);
Console.WriteLine(alert.Status);
}
}
}
}
}
Currently, I loop through each several times and use if to check field and then assign value to a variable. Then I have to loop through it again. Is there an easier way, and should I use plain LINQ or LINQ-TO-XML?
Anonymous User
28-Sep-2013Hey Ida!
If you want to traverse it like that you can: